package com.zyf.system.controller;

import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.zyf.system.controller.dto.BasePageDto;
import com.zyf.system.controller.dto.DoctorPageDto;
import com.zyf.system.controller.dto.DoctorUpdateDto;
import com.zyf.system.db.mysql.Doctor;
import com.zyf.system.db.mysql.QDepartment;
import com.zyf.system.db.mysql.QDoctor;
import com.zyf.system.db.mysql.QUser;
import com.zyf.system.repository.DepartmentRepository;
import com.zyf.system.repository.DoctorRepository;
import com.zyf.system.repository.UserRepository;
import com.zyf.system.until.Constant;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 张云帆
 * 2025/4/1 9:41
 */
@RestController
@RequestMapping("/doctor")
public class DoctorController extends BaseController{
    @Autowired
    private DoctorRepository doctorRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private DepartmentRepository departmentRepository;
    private final QDoctor qDoctor = QDoctor.doctor;
    private final QUser quser = QUser.user;

    @PostMapping("/page")
    @ApiOperation(value = "分页查询医生列表")
    public Map<String, Object> page(@Validated @RequestBody DoctorPageDto doctorPageDto){
        try {
            Pageable pageable = PageRequest.of(doctorPageDto.getPageNum() - 1, doctorPageDto.getPageSize());
            Predicate predicate = qDoctor.isDeleted.isFalse();
            if(doctorPageDto.getUsername() != null){
                Predicate userPredicate = quser.username.like("%"+doctorPageDto.getUsername()+"%");
                List<Integer> userIdList = new ArrayList<>();
                userRepository.findAll(userPredicate).forEach(user -> {
                    userIdList.add(user.getId());
                });
                if(!userIdList.isEmpty()){
                    predicate = ExpressionUtils.and(predicate,qDoctor.userId.in(userIdList));
                }
            }
            if(doctorPageDto.getDepartmentId()!=null){
                predicate = ExpressionUtils.and(predicate,qDoctor.departmentId.eq(doctorPageDto.getDepartmentId()));
            }
            if(doctorPageDto.getTitle() != null){
                predicate = ExpressionUtils.and(predicate,qDoctor.title.like("%"+doctorPageDto.getTitle()+"%"));
            }
            if(doctorPageDto.getRealName() != null){
                Predicate userPredicate = quser.realName.like("%"+doctorPageDto.getRealName()+"%");
                List<Integer> userIdList = new ArrayList<>();
                userRepository.findAll(userPredicate).forEach(user -> {
                    userIdList.add(user.getId());
                });
                if(!userIdList.isEmpty()){
                    predicate = ExpressionUtils.and(predicate,qDoctor.userId.in(userIdList));
                }
            }
            return createResponse(Constant.SUCCESS, "分页查询医生列表成功", doctorRepository.findAll(predicate,pageable));
        }catch (Exception e){
            return createResponse(Constant.FAIL, "分页查询医生列表异常", e.getMessage());
        }
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改医生信息")
    public Map<String, Object> update(@Validated @RequestBody DoctorUpdateDto doctorUpdateDto){
        try {
            Doctor doctor = doctorRepository.findById(doctorUpdateDto.getId()).orElse(null);
            if(doctor == null){
                return createResponse(Constant.FAIL, "医生不存在", null);
            }
            if(doctorUpdateDto.getDepartmentId() != null){
                if(!departmentRepository.existsById(doctorUpdateDto.getDepartmentId())){
                    return createResponse(Constant.FAIL, "科室不存在", null);
                }
                doctor.setDepartmentId(doctorUpdateDto.getDepartmentId());
            }
            if(doctorUpdateDto.getTitle() != null){
                doctor.setTitle(doctorUpdateDto.getTitle());
            }else doctor.setTitle("");
            if(doctorUpdateDto.getSpecialty() != null){
                doctor.setSpecialty(doctorUpdateDto.getSpecialty());
            }else doctor.setSpecialty("");
            return createResponse(Constant.SUCCESS, "修改医生信息成功", doctorRepository.save(doctor));
        }catch (Exception e){
            return createResponse(Constant.FAIL, "修改医生信息异常", e.getMessage());
        }
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "注销医生账户")
    public Map<String, Object> delete(@Validated @NotNull @RequestParam Integer id){
        try {
            Doctor doctor = doctorRepository.findById(id).orElse(null);
            if(doctor == null){
                return createResponse(Constant.FAIL, "医生不存在", null);
            }
            doctor.setIsDeleted(true);
            return createResponse(Constant.SUCCESS, "注销医生账户成功", doctorRepository.save(doctor));
        }catch (Exception e){
            return createResponse(Constant.FAIL, "注销医生账户异常", e.getMessage());
        }
    }

    @GetMapping("/get")
    @ApiOperation(value = "获取医生信息")
    public Map<String, Object> get(@Validated @NotNull @RequestParam Integer id){
        try {
            Doctor doctor = doctorRepository.findById(id).orElse(null);
            if(doctor == null){
                return createResponse(Constant.FAIL, "医生不存在", null);
            }
            if(userRepository.exists(quser.id.eq(doctor.getUserId()).and(quser.isDeleted.isTrue()))){
                return createResponse(Constant.FAIL, "医生已被注销", null);
            }
            return createResponse(Constant.SUCCESS, "获取医生信息成功", doctor);
        }catch (Exception e){
            return createResponse(Constant.FAIL, "获取医生信息异常", e.getMessage());
        }
    }
}
